Cuestionario Ampliado del Censo de Población y Vivienda 2010

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Cuestionario Ampliado_2010_Persona.sav")

save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2010.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

Posibles variables que se pueden contemplar en la migración laboral

  • EDAD

  • SEXO

  • HLENGUA

  • QDIALECT_C

  • PERETN

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • ALFABET

  • ESTCONL

  • NUMHIJ

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • CONACT Condición de actividad

load(paste0(here::here(), "/Bases/Censo_Personas_2010.RData"))

mydata <- data %>%
           select(ENT, NOM_ENT, MUN, NOM_MUN, ENT_MUN, LTRABPAI_C, LTRABMUN_C, ENT_MUN_TRABAJO,
                  EDAD, SEXO, HLENGUA, QDIALECT_C, LI_INALI, PERETN, NIVACAD, ALFABET, 
                  ESTCON, CONACT, NUMHIJ, FACTOR, ESTRATO, UPM) %>%
            rename("CVE_ENT" = "ENT",
                   "CVE_MUN" = "ENT_MUN",
                   "ENT_PAIS_TRAB" = "LTRABPAI_C",
                   "MUN_TRAB" = "LTRABMUN_C",
                   "CVE_MUN_TRAB" = "ENT_MUN_TRABAJO") %>%
             mutate(CVE_ENT = str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"))

save(mydata, file = paste0(here::here(), "/Bases/03_Movilidad laboral_2010.RData"))

✔️A partir de aquí se pueden correr los códidos 👇.
Se carga el archivo Migracion laboral_2010.RData.

load(file = paste0(here::here(), "/Bases/03_Movilidad laboral_2010.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>% 
           select(CVE_ENT, NOM_ENT, MUN, NOM_MUN, CVE_MUN, ENT_PAIS_TRAB, MUN_TRAB, CVE_MUN_TRAB,
                  CONACT, EDAD, FACTOR, ESTRATO, UPM) %>%
            rename("CVE_MUN_TRABAJO" = "CVE_MUN_TRAB") %>%
            mutate(M = 1)  %>%
             ungroup()

Claves de entidades y municipios

Entidades Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)

nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")

est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2010.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()

# Se le asignan las etiquetas a los nombres de los estados 
levels(mydata$NOM_ENT) <- estados

Población ocupada de 12 años y más

Se identifica a la población ocupada de 12 años y más.

filter((EDAD >= 12 & EDAD != 999) & (CONACT >= 10 & CONACT <= 20))'.

Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   filter(CVE_MUN_TRABAJO %in% municipios)  # Filtro del lugar de trabajo dentro del país. 

Población ocupada de 12 años y más

Población economicámente activa de 12 años y más

Nivel estatal

Migración laboral

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población ocupada de 12 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       as.data.frame() %>%
        mutate(EDAD = as.numeric(.$EDAD)) %>%
         subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
          filter(ENT_PAIS_TRAB %in% estados) %>%
           svydesign(data = ., id = ~UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/MC_estado.RDS"))

Se genera una matriz cruzada de migración laboral a nivel estatal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/MC_estado.RDS"))

Migrantes <- svytable(~ENT_PAIS_TRAB + CVE_ENT, design = MC)

La función cross_cases() de la paquetería expss se utiliza para crear tablas de contingencia cruzadas a partir de dos o más variables categóricas. Utilizando el comando weight, permite ponderar las observaciones “factores de expansión” en la tabla.

Se quita la diagonal a la matriz cruadrada con la función diag.remove() de la paquetería sna, donde esta función reemplaza los elementos de la diagonal principal de una matriz por un valor nulo o por el valor especifico.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ENT, ENT_PAIS_TRAB, weight = Freq) %>%
                as.data.frame() %>%
                 slice(-33) %>% 
                  select(-row_labels) 

rownames(Migrantes)<- nom_estados
colnames(Migrantes) <- nom_estados

save(Migrantes, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

wb <- createWorkbook()
addWorksheet(wb, "MTrabajo 2010")
writeData(wb, 1, Migrantes, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel estatal, 2010

Matriz de migración laboral, 2010
Nivel estatal
Entidad Aguascalientes Baja California Baja California Sur Campeche Coahuila de Zaragoza Colima Chiapas Chihuahua Ciudad de México Durango Guanajuato Guerrero Hidalgo Jalisco México Michoacán de Ocampo Morelos Nayarit Nuevo León Oaxaca Puebla Querétaro Quintana Roo San Luis Potosí Sinaloa Sonora Tabasco Tamaulipas Tlaxcala Veracruz de Ignacio de la Llave Yucatán Zacatecas
Aguascalientes 432034 33 0 59 39 0 0 4 1288 8 721 29 12 2612 556 139 29 21 203 20 46 158 28 550 0 12 37 8 20 90 0 3374
Baja California 0 1235596 766 26 27 0 76 119 633 0 4 34 26 307 226 163 0 64 77 0 0 59 0 0 407 2020 0 155 0 32 11 0
Baja California Sur 0 250 280185 16 4 0 70 35 299 0 72 0 0 96 2230 21 0 0 0 0 0 22 70 0 22 17 0 0 0 70 0 0
Campeche 0 23 0 310398 31 16 105 0 286 5 7 0 2 16 141 0 0 0 33 0 5 0 1001 0 33 0 484 16 0 95 2381 0
Coahuila de Zaragoza 250 8 22 0 984331 16 0 589 783 15159 215 32 78 277 474 25 98 21 6324 44 63 277 63 105 12 265 44 806 0 150 0 1050
Colima 100 45 84 50 9 280236 7 103 430 4 109 50 2 3209 176 1379 7 12 96 7 1 14 5 0 71 15 6 0 0 26 2 53
Chiapas 0 322 9 705 17 143 1533588 141 1428 52 185 106 19 325 886 64 6 371 226 913 330 25 1360 3 196 430 4584 110 5 775 164 13
Chihuahua 16 65 10 25 667 13 67 1258768 784 601 10 16 0 312 420 11 12 0 575 192 38 76 2 46 283 290 1 135 7 112 0 140
Ciudad de México 120 258 49 243 286 170 542 491 3572953 254 869 881 3069 2351 182612 1323 3851 116 778 625 2724 2555 1006 606 1211 176 369 488 493 1887 138 114
Durango 79 49 0 46 19054 7 0 809 240 506416 32 25 52 161 191 16 4 133 563 1 25 36 23 75 420 191 6 39 0 212 0 800
Guanajuato 822 128 38 271 110 170 25 475 2691 63 1915870 73 141 2698 1478 4438 5 57 516 52 300 18769 90 3375 60 500 22 230 33 268 52 681
Guerrero 29 125 448 68 14 99 41 159 2238 38 174 1111081 104 528 2004 1588 2044 33 43 448 343 49 45 30 616 407 44 85 3 217 1 109
Hidalgo 92 85 22 357 289 124 105 302 21148 330 642 283 895594 903 23264 287 337 47 1459 195 1540 3245 45 736 303 126 103 598 997 2995 110 323
Jalisco 4734 523 98 74 9 3781 888 106 2724 126 3153 47 143 2896853 1315 3969 23 7106 582 92 96 211 49 180 706 182 195 197 5 202 0 1382
México 432 566 226 655 865 251 1259 1063 1204317 582 2894 1872 26469 3707 4478284 3172 7268 388 2761 1780 5344 9398 733 1008 486 840 676 1037 1127 4332 71 621
Michoacán de Ocampo 62 218 63 32 62 452 63 64 4739 41 6722 1465 105 4865 6122 1489261 214 162 166 82 157 1150 17 92 116 148 54 55 20 248 89 208
Morelos 23 26 23 66 74 18 249 411 14770 31 15 2425 11 85 5543 99 682207 15 141 61 2051 185 130 52 10 271 101 11 25 659 10 62
Nayarit 0 191 24 17 61 3 10 11 245 26 101 15 0 10466 124 86 67 398010 10 26 20 0 0 57 771 408 24 0 0 93 0 37
Nuevo León 46 273 0 107 3524 1 162 376 2121 98 295 89 182 562 1574 153 207 0 1786143 1 335 379 63 521 91 278 288 3387 0 663 114 4327
Oaxaca 20 257 84 879 21 50 558 92 3215 53 70 416 94 176 1979 61 116 112 355 1232912 1240 95 136 22 307 340 242 80 13 4382 67 43
Puebla 281 400 304 445 100 207 472 370 16102 55 378 1071 2170 757 10694 505 1694 72 1358 2906 1992848 498 319 161 182 2916 505 469 7904 8943 191 371
Querétaro 70 142 7 70 13 5 154 198 3925 0 5481 20 1888 419 2784 628 82 20 428 259 168 693610 0 377 18 6 126 189 92 334 19 97
Quintana Roo 0 125 0 345 1 0 0 0 393 0 0 0 9 21 130 1 0 0 27 0 193 0 562000 0 8 0 66 15 0 15 883 0
San Luis Potosí 365 0 7 174 691 57 4 145 1437 164 1193 40 226 923 768 130 40 33 6705 12 108 1063 72 864255 317 83 64 3072 14 1013 17 2029
Sinaloa 0 884 520 388 17 41 151 514 345 415 102 13 18 579 216 194 0 483 283 75 0 20 53 38 954054 4890 82 9 6 49 0 115
Sonora 19 2362 277 0 18 14 20 1040 905 15 55 2 2 627 201 18 0 22 185 22 41 57 0 8 1075 978197 66 12 0 22 0 75
Tabasco 0 22 0 6776 21 18 8897 136 401 0 0 16 0 40 263 0 0 89 124 33 86 242 1066 8 21 51 752623 263 0 1892 197 0
Tamaulipas 13 40 26 2725 288 115 75 78 1238 159 144 45 194 214 707 10 0 36 4194 166 91 62 97 1835 14 80 123 1180907 4 5999 0 70
Tlaxcala 12 129 75 134 25 3 94 52 6625 19 154 216 836 291 4972 150 417 19 431 299 39630 203 57 111 143 165 127 212 387423 1298 33 52
Veracruz de Ignacio de la Llave 137 315 333 10641 402 155 1128 665 10220 133 272 200 2714 563 7221 515 190 79 1756 4697 7943 334 1222 843 695 987 3612 14175 228 2658206 181 128
Yucatán 115 0 3 2784 97 0 72 0 1831 38 71 0 22 176 193 61 8 0 212 13 188 2 13698 1 16 8 450 15 17 329 746493 12
Zacatecas 4835 84 79 8 391 6 11 179 322 493 201 9 6 1555 178 24 30 42 394 13 61 36 62 1816 62 194 117 68 0 45 14 467109
Fuente: Estimaciones del CONAPO.

Gráfico dinámico

Gráfico dinámico de migración laboral a nivel estatal.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

names <- c("Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila", "Colima", 
           "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",    
           "México", "Michoacán", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
           "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
           "Veracruz", "Yucatán", "Zacatecas")

# Paleta de colores
paleta <- colorRampPalette(pals::ocean.matter(100))(50)

p <- chorddiag(tabla, 
               groupNames = names,
               groupColors = paleta, 
               groupnamePadding = 10, 
               #height = 700, 
               #width = 700,
               margin = 120,
               groupThickness = 0.07,
               groupPadding = 3,
               groupnameFontsize = 12,
               fadeLevel = '0.1',
               tickInterval = seq(0, 500000, 10000),
               chordedgeColor = "transparent",
               showZeroTooltips = FALSE,
               showTicks = TRUE)

# Ajusta las etiquetas usando JavaScript para modificar su posición
p <- htmlwidgets::onRender(p, '
      function(el, x) {
        d3.selectAll(".group text")
          .attr("text-anchor", "middle")
          .attr("dx", "0")  
          .attr("dy", "0.75em"); 
      }
')

# Crear un contenedor div y aplicar estilos CSS para centrarlo
#p <- tags$div(style = "display: flex; justify-content: center; align-items: center;", p)

p
p %>% 
 mapshot(url = paste0(here::here(),"/images/MTrab_2010.html"))

#htmlwidgets::saveWidget(p, paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2010/MTrab a nivel estatal 2010.html"), selfcontained = TRUE)
#require(webshot)
#webshot(url = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2010/MTrab a nivel estatal 2010.html"),
 #         file = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2010/MTrab a nivel estatal 2010.png"),
  #                cliprect = "viewport")

Gráficos migración laboral

ChordDiagram

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0)  

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Paleta de colores
#paleta <- colorRampPalette(pals::ocean.matter(100))(50)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2010/ChordDiagram de MTrab a nivel estatal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0.4,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) 

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#filtro_mig <- sapply(1:32, function(x)
 #                     mean(tail(sort(tabla1[[x]]), 1), na.rm = TRUE))
#p <- data.frame(estados = est,
 #               filtro_estados = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Filtro a nivel estatal.xlsx"))

filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Filtro a nivel estatal.xlsx"), colNames = TRUE) %>% 
               pull(filtro_estados)

tabla1 <- migration_flows_states(tabla = tabla, 
                                 filtro_mig = filtro_mig, 
                                 filtro_est = filtro_est, 
                                 category = estado, 
                                 group = "Otro estados")

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                 name = "Total",,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Matriz MTrab por estados_2010_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Tabla MTrab por estados.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Tabla MTrab por estados.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_ENT", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_ENT", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(),  "/Output/Estado/03_Movilidad laboral/2010/Matriz MTrab por estados_2010_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Tabla MTrab por estados.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2010/ChordDiagram de MTrab para cada estado.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Estado/03_Movilidad laboral/2010/Etiquetas a nivel estatal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(nom_estados))

Gráfico Sankey

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

Migrantes <- Migrantes %>%
              sna::diag.remove(remove.val = 0)  

rownames(Migrantes) <- stringr::str_wrap(nom_estados, 50)
colnames(Migrantes) <- stringr::str_wrap(nom_estados, 50)

# Matiz movilidad laboral (Población de 12 años y más)
tabla <- Migrantes %>% 
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             as_tibble() %>%
              mutate(rn = forcats::fct_relevel(.$rn, nom_estados),
                     cn = forcats::fct_relevel(.$cn, nom_estados)) %>%
               filter(value >= 0)  
p <- tabla %>% 
       ggplot(aes(axis1 = rn, 
                   axis2 = cn, 
                    y = value),  # c("value", "freq", "tasa")
               reverse = FALSE, 
                na.rm = TRUE) +
        geom_alluvium(aes(fill = rn),
                       curve_type = "quintic", 
                        color = "transparent", 
                         alpha = 0.85, 
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
          geom_stratum(aes(fill = cn), 
                        color = "white", 
                         alpha = 0.65,  
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.2,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .2, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() + 
              theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(1, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.35)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2010/GSankey de MTrab a nivel estatal.pdf")
ggexport(p, width = 14, height = 10, dpi = 400, filename = path)

Desagregado por estado

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% estados | .$cn %in% estados), value, 0)) %>%
                mutate(rn = forcats::fct_relevel(.$rn, estados),
                       cn = forcats::fct_relevel(.$cn, estados)) 
p <- lapply(1:32, function(x){
                   tabla <- tabla %>%
                             mutate(rn = forcats::fct_relevel(.$rn, estados),
                                    cn = forcats::fct_relevel(.$cn, estados)) %>%
                              mutate(value = ifelse(.$rn %in% estados[x] | .$cn %in% estados[x], value, 0)) 
 
                    tabla %>% 
                     ggplot(aes(axis1 = rn, 
                                 axis2 = cn, 
                                  y = value),  # c("value", "freq", "tasa")
                             reverse = FALSE, 
                              na.rm = TRUE) + 
                      geom_alluvium(aes(fill = rn),  
                                     color = "transparent", 
                                      alpha = 0.8, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                       geom_stratum(aes(fill = rn), 
                                     color = "#F1F1F1", 
                                      alpha = 1, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                         geom_text_repel(aes(label = ifelse(after_stat(x)  == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                             fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = -.2, 
                                               force = 1,
                                                        force_pull = 0,
                                                         family = "montserrat",
                                                          reverse = FALSE) +
                          geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                              fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = .2, 
                                               force = 1,
                                                force_pull = 0,
                                                 family = "montserrat",
                                                  reverse = FALSE) +
                            theme_void() + 
                             theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                    text = element_text(family = "montserrat"),
                                     axis.text = element_blank(),
                                      axis.title = element_blank(),
                                       strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                        legend.key.size = unit(0.5, "cm"),
                                         legend.text = element_text(size = 9, family = "montserrat"),
                                          legend.position = c(1, .5)) + 
                              scale_x_discrete(expand = c(-0.1, 0.35)) +
                               scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                                guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                                 labs(fill = "", 
                                      color = "")
              }
  )

path = paste0(here::here(),"/Graficos/Estado/03_Movilidad laboral/2010/GSankey de MTrab desagregado por estados_Absolutos.pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ENT) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población ocupada de 12 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_ENT) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2010/Matriz de MTrab a nivel estatal 2010.RData"))

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                tidyr::gather(CVE_ENT, Value, -rowname)%>%
                 filter(rowname == CVE_ENT) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos laborales
Inmigrantes <- Migrantes %>% 
                sna::diag.remove(remove.val = 0) %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "CVE_ENT") %>%
                   melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                    mutate_at(vars(3), as.numeric) %>%
                     as_tibble() %>%
                      filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                       group_by(CVE_ENT) %>%
                        summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               sna::diag.remove(remove.val = 0) %>%
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_ENT") %>%
                  melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                      group_by(ENT_PAIS_TRAB) %>%
                       summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                        rename("CVE_ENT" = "ENT_PAIS_TRAB")

tabla <- Pob.Total %>%
          left_join(., Pob.ocupada, by = c("CVE_ENT")) %>%
          left_join(., Residentes, by = c("CVE_ENT")) %>%
          left_join(., Inmigrantes, by = c("CVE_ENT")) %>%
          left_join(., Emigrantes, by = c("CVE_ENT")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Indicadores de MTrab a nivel estatal 2010.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2010/Indicadores de MTrab a nivel estatal 2010.RData"))
Indicadores de movilidad laboral
Nivel estatal
CVE_ENT Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001 1 178 800 447 267 432 034 10 096 12 672 −2 576 22 768 2.5 3.1 −0.6 −25 344
002 3 123 385 1 310 850 1 235 596 5 232 7 948 −2 716 13 180 0.5 0.7 −0.2 −15 896
003 633 854 287 285 280 185 3 294 3 597 −303 6 891 1.4 1.6 −0.1 −7 194
004 816 916 319 408 310 398 4 680 28 186 −23 506 32 866 1.6 9.9 −8.3 −56 372
005 2 739 691 1 037 370 984 331 27 250 27 227 23 54 477 2.9 2.9 0.0 −54 454
006 647 654 288 965 280 236 6 072 5 935 137 12 007 2.6 2.5 0.1 −11 870
007 4 788 162 1 583 966 1 533 588 13 913 15 305 −1 392 29 218 0.9 1.0 −0.1 −30 610
008 3 390 459 1 297 487 1 258 768 4 926 8 727 −3 801 13 653 0.4 0.7 −0.3 −17 454
009 8 783 909 3 914 834 3 572 953 210 655 1 308 123 −1 097 468 1 518 778 6.6 41.2 −34.6 −2 616 246
010 1 624 841 542 141 506 416 23 289 18 962 4 327 42 251 4.3 3.5 0.8 −37 924
011 5 474 270 1 991 822 1 915 870 38 631 24 341 14 290 62 972 2.1 1.3 0.8 −48 682
012 3 380 094 1 146 530 1 111 081 12 174 9 490 2 684 21 664 1.1 0.8 0.2 −18 980
013 2 674 391 973 886 895 594 61 392 38 594 22 798 99 986 6.7 4.2 2.5 −77 188
014 7 323 176 2 992 334 2 896 853 32 898 39 821 −6 923 72 719 1.3 1.5 −0.3 −79 642
015 15 123 304 5 899 987 4 478 284 1 286 200 259 642 1 026 558 1 545 842 24.5 4.9 19.5 −519 284
016 4 348 993 1 551 250 1 489 261 28 053 19 230 8 823 47 283 1.9 1.3 0.6 −38 460
017 1 769 804 723 383 682 207 27 653 16 749 10 904 44 402 4.4 2.7 1.7 −33 498
018 1 075 926 415 518 398 010 12 893 9 553 3 340 22 446 3.5 2.6 0.9 −19 106
019 4 641 903 1 855 044 1 786 143 20 217 31 005 −10 788 51 222 1.2 1.9 −0.7 −62 010
020 3 784 250 1 278 752 1 232 912 15 575 13 034 2 541 28 609 1.2 1.0 0.2 −26 068
021 5 778 539 2 099 846 1 992 848 62 800 63 167 −367 125 967 3.2 3.2 0.0 −126 334
022 1 825 636 727 741 693 610 18 019 39 220 −21 201 57 239 2.8 6.1 −3.3 −78 440
023 1 319 485 577 897 562 000 2 232 21 512 −19 280 23 744 0.5 4.5 −4.1 −43 024
024 2 574 788 907 069 864 255 20 966 12 656 8 310 33 622 2.4 1.5 1.0 −25 312
025 2 760 401 986 392 954 054 10 500 8 672 1 828 19 172 1.1 0.9 0.2 −17 344
026 2 632 996 1 008 869 978 197 7 160 16 296 −9 136 23 456 0.8 1.8 −1.0 −32 592
027 2 236 189 791 373 752 623 20 662 12 618 8 044 33 280 2.7 1.7 1.1 −25 236
028 3 254 638 1 241 167 1 180 907 18 842 25 936 −7 094 44 778 1.7 2.3 −0.6 −51 872
029 1 180 714 452 336 387 423 56 984 11 013 45 971 67 997 14.0 2.7 11.3 −22 026
030 7 626 403 2 782 400 2 658 206 72 684 37 447 35 237 110 131 2.8 1.4 1.4 −74 894
031 1 952 423 777 466 746 493 20 432 4 745 15 687 25 177 3.0 0.7 2.3 −9 490
032 1 494 145 488 936 467 109 11 335 16 286 −4 951 27 621 2.3 3.3 −1.0 −32 572
Fuente: Estimaciones del CONAPO.

Nivel municipal

Movilidad laboral

Matrices

#Clave de los municipios 2010 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                    nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de trabajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(EDAD = as.numeric(.$EDAD)) %>%
                   subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20) 
                          ) %>%
                    select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT) %>%
                     filter(CVE_MUN_TRABAJO %in% municipios) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel municipal 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel municipal 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Laboral")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel municipal 2010.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2010 - 2010

Matriz de movilidad laboral
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 306788 279 562 4 2524 406 449 0 62 97 1378 0 0 0 33 0 0 0 0 0 0 0 18 0 0 0 0 0 0
001002 798 8854 0 0 64 8 74 0 138 27 218 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 204 0 17419 0 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 220 8 26 2945 42 10 201 0 17 0 154 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7485 0 265 0 23334 103 102 44 0 0 459 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 989 56 24 24 358 8716 294 128 226 38 1243 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 630 54 27 142 194 194 11750 40 162 0 543 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 144 0 2 6 14 50 32 1748 6 6 22 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 580 33 23 33 92 76 682 5 3186 0 328 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 755 66 8 0 8 0 8 0 8 3181 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2738 40 8 0 580 488 142 24 66 0 7383 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 189915 246 298 655 264 0 53 28 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 184 364575 155 436 54 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 57 84 36014 740 21 13 0 7 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 1695 1252 1013 593340 3626 0 169 311 28 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 231 45 59 4263 30726 0 10 16 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 18 0 0 0 0 27645 54 177 66 102 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 30 0 0 0 0 15 24457 15 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 14 0 19 0 141 131 107221 738 82 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 70 0 5 0 416 111494 140 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 7 7 7 7 7258 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18245 220 258 262 176 110 0 88
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 82 102084 1347 470 11 39 0 141
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85988 0 0 17 72 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 154 606 27994 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 146 205 211 116 7330 50 5 140
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 212 111 27 0 12037 7 14
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 0 0 0 3051 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 132 28 14 49 3 3 2882
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 33 111 0 0 0 11 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel municipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)      

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE))

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#### Se anexa el filtro de estados filter(value > 100000000 & rn != estado[x]) %>% 
#### De esta manera solo se contemplan a los municipios
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                         tabla1[[i]] %>%
#                          as.data.frame() %>%
#                           adorn_totals(c("row", "col"), 
#                                         fill = "-", 
#                                          na.rm = TRUE, 
#                                           ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                            select(`Otros estados`) %>%
#                             slice(nrow(.)) %>%
#                              mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                               pull(`Otros estados`)
# })

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                   tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      adorn_totals(c("row", "col"), 
#                                                    fill = "-", 
#                                                     na.rm = TRUE, 
#                                                      ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                       slice(nrow(.)) %>%
#                                        mutate(Total = .$Total/50) %>%
#                                        pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb,  
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel municipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2010/ChordDiagram de MTrab desagregado por municipio.pdf"

## Gráficos a nivel municipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2010/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 10, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
############# Población ocupada de 12 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel municipal 2010.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de movilidad laboral a nivel municipal 2010.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de movilidad laboral a nivel municipal 2010.RData"))
Indicadores de movilidad laboral
Nivel municipal
Clave de Entidad-Municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 322 616 306 788 9 495 21 310 −11 815 30 805 3.40 7.63 −4.2 −42 620
001002 45 951 12 604 8 854 1 960 714 1 246 2 674 13.39 4.88 8.5 −1 428
001003 53 142 18 510 17 419 370 1 034 −664 1 404 2.07 5.77 −3.7 −2 068
001004 14 302 4 350 2 945 821 281 540 1 102 17.61 6.03 11.6 −562
001005 100 150 35 777 23 334 8 800 4 090 4 710 12 890 25.90 12.04 13.9 −8 180
001006 40 480 13 230 8 716 3 504 1 373 2 131 4 877 26.10 10.23 15.9 −2 746
001007 48 462 15 781 11 750 2 498 2 204 294 4 702 15.55 13.72 1.8 −4 408
001008 7 164 2 114 1 748 288 258 30 546 12.42 11.12 1.3 −516
001009 20 048 5 254 3 186 1 930 711 1 219 2 641 30.51 11.24 19.3 −1 422
001010 18 282 4 668 3 181 937 464 473 1 401 16.33 8.09 8.2 −928
001011 36 822 12 363 7 383 4 196 4 727 −531 8 923 34.12 38.44 −4.3 −9 454
002001 460 793 197 111 189 915 1 827 2 717 −890 4 544 1.11 1.65 −0.5 −5 434
002002 932 001 384 781 364 575 1 835 3 145 −1 310 4 980 0.56 0.96 −0.4 −6 290
002003 95 638 39 811 36 014 1 004 1 567 −563 2 571 2.96 4.63 −1.7 −3 134
002004 1 543 644 650 723 593 340 8 636 8 610 26 17 246 1.57 1.57 0.0 −17 220
002005 91 309 38 424 30 726 4 697 4 009 688 8 706 14.48 12.36 2.1 −8 018
003001 70 358 28 691 27 645 417 215 202 632 1.68 0.87 0.8 −430
003002 58 624 24 829 24 457 75 472 −397 547 0.36 2.26 −1.9 −944
003003 249 303 109 569 107 221 1 199 1 599 −400 2 798 1.34 1.78 −0.4 −3 198
003008 238 498 116 768 111 494 973 1 910 −937 2 883 1.10 2.15 −1.1 −3 820
Fuente: Estimaciones del CONAPO.

Movilidad Intramunicipal

Matrices

#Clave de los municipios 2010 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de tranajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 1) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_intramunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2010

Matriz de movilidad laboral
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 306788 279 562 4 2524 406 449 0 62 97 1378 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 798 8854 0 0 64 8 74 0 138 27 218 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 204 0 17419 0 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 220 8 26 2945 42 10 201 0 17 0 154 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7485 0 265 0 23334 103 102 44 0 0 459 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 989 56 24 24 358 8716 294 128 226 38 1243 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 630 54 27 142 194 194 11750 40 162 0 543 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 144 0 2 6 14 50 32 1748 6 6 22 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 580 33 23 33 92 76 682 5 3186 0 328 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 755 66 8 0 8 0 8 0 8 3181 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2738 40 8 0 580 488 142 24 66 0 7383 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 189915 246 298 655 264 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 184 364575 155 436 54 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 57 84 36014 740 21 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 1695 1252 1013 593340 3626 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 231 45 59 4263 30726 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27645 54 177 66 102 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 24457 15 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 141 131 107221 738 82 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 416 111494 140 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 7 7 7 7258 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18245 220 258 262 176 110 0 88
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 82 102084 1347 470 11 39 0 141
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85988 0 0 17 72 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 154 606 27994 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 146 205 211 116 7330 50 5 140
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 212 111 27 0 12037 7 14
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 0 0 0 3051 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 132 28 14 49 3 3 2882
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 33 111 0 0 0 11 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)   

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig)
#write.table(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)

################################################################################
## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                  tabla1[[i]] %>%
#                                   as.data.frame() %>%
#                                    adorn_totals(c("row", "col"), 
#                                                  fill = "-", 
#                                                   na.rm = TRUE, 
#                                                    ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(Total) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(Total = .$Total/100) %>%
 #}
#)

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
 
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intramunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2010/ChordDiagram de Mtrab desagregado a nivel intramunicipal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2010/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 0) %>% 
               pull(rn)
################################################################################

tabla1 <- lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ substr(.$rn, 1, 3)),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ substr(.$cn, 1, 3))) %>%

                     mutate(value = ifelse(.$rn != .$cn, .$value, 0)) %>%
                      filter(value > 0) 
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)
p[[3]]
path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2010/GSankey de MR5a desagregado a nivel intramunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 12 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intramunicipal 2010.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de MTrab a nivel intramunicipal 2010.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de MTrab a nivel intramunicipal 2010.RData"))
Indicadores de movilidad laboral
Nivel intramunicipal
Clave de Entidad-Municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 322 616 306 788 5 761 14 543 −8 782 20 304 2.06 5.21 −3.1 −29 086
001002 45 951 12 604 8 854 1 327 536 791 1 863 9.06 3.66 5.4 −1 072
001003 53 142 18 510 17 419 237 945 −708 1 182 1.32 5.28 −4.0 −1 890
001004 14 302 4 350 2 945 678 209 469 887 14.54 4.48 10.1 −418
001005 100 150 35 777 23 334 8 458 3 909 4 549 12 367 24.89 11.50 13.4 −7 818
001006 40 480 13 230 8 716 3 380 1 335 2 045 4 715 25.17 9.94 15.2 −2 670
001007 48 462 15 781 11 750 1 986 1 984 2 3 970 12.37 12.35 0.0 −3 968
001008 7 164 2 114 1 748 282 241 41 523 12.16 10.39 1.8 −482
001009 20 048 5 254 3 186 1 852 685 1 167 2 537 29.28 10.83 18.4 −1 370
001010 18 282 4 668 3 181 880 168 712 1 048 15.34 2.93 12.4 −336
001011 36 822 12 363 7 383 4 086 4 372 −286 8 458 33.23 35.56 −2.3 −8 744
002001 460 793 197 111 189 915 1 463 2 167 −704 3 630 0.89 1.32 −0.4 −4 334
002002 932 001 384 781 364 575 829 1 627 −798 2 456 0.25 0.49 −0.2 −3 254
002003 95 638 39 811 36 014 902 1 525 −623 2 427 2.66 4.50 −1.8 −3 050
002004 1 543 644 650 723 593 340 7 586 6 094 1 492 13 680 1.38 1.11 0.3 −12 188
002005 91 309 38 424 30 726 4 598 3 965 633 8 563 14.18 12.23 2.0 −7 930
003001 70 358 28 691 27 645 399 168 231 567 1.61 0.68 0.9 −336
003002 58 624 24 829 24 457 30 192 −162 222 0.14 0.92 −0.8 −384
003003 249 303 109 569 107 221 1 092 615 477 1 707 1.22 0.69 0.5 −1 230
003008 238 498 116 768 111 494 561 811 −250 1 372 0.63 0.91 −0.3 −1 622
Fuente: Estimaciones del CONAPO.

Movilidad Intermunicipal

Matrices

#Clave de los municipios 2010 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Entidad de trabajo en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de trabajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 2) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_intermunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2010

Matriz de movilidad laboral
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 0 0 0 0 0 0 0 18 0 0 0 0 0 0
001002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 53 28 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 13 0 7 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 169 311 28 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 16 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 14 0 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 70 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
municipios <- MUN %>% 
               mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                pull(municipios)
             
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2010/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                                 tabla1[[i]] %>%
#                                  as.data.frame() %>%
#                                   adorn_totals(c("row", "col"), 
#                                                 fill = "-", 
#                                                  na.rm = TRUE, 
#                                                   ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(`Otros estados`) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                       pull(`Otros estados`)
#})


## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                               tabla1[[i]] %>%
#                                as.data.frame() %>%
#                                 select(-c(`Otros estados`)) %>%
#                                  adorn_totals(c("row", "col"), 
#                                                fill = "-", 
#                                                 na.rm = TRUE, 
#                                                  ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    slice(nrow(.)) %>%
#                                     mutate(Total = .$Total/50) %>%
#                                      pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
 wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz MTrab a nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Tabla MTrab a nivel intermunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2010/ChordDiagram de Mtrab desagregado a nivel intermunicipal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2010/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 5000) %>% 
               pull(rn)
################################################################################

tabla1 <-  lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                     mutate(value = ifelse(.$rn != .$cn & (substr(.$rn, 1, 3) %in% estados[x] | substr(.$cn, 1, 3) %in% estados[x]), .$value, 0)) %>%
                      filter(value > 0)  
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2010/GSankey de MR5a desagregado a nivel intermunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 12 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 12 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Matriz de movilidad laboral a nivel intermunicipal 2010.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de MTrab a nivel intermunicipal 2010.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2010/Indicadores de MTrab a nivel intermunicipal 2010.RData"))
Indicadores de movilidad laboral
Nivel intermunicipal
Clave de Entidad-Municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 793 997 322 616 0 3 734 6 767 −3 033 10 501 1.338 2.42 −1.1 −13 534
001002 45 951 12 604 0 633 178 455 811 4.324 1.22 3.1 −356
001003 53 142 18 510 0 133 89 44 222 0.742 0.50 0.2 −178
001004 14 302 4 350 0 143 72 71 215 3.067 1.54 1.5 −144
001005 100 150 35 777 0 342 181 161 523 1.006 0.53 0.5 −362
001006 40 480 13 230 0 124 38 86 162 0.923 0.28 0.6 −76
001007 48 462 15 781 0 512 220 292 732 3.188 1.37 1.8 −440
001008 7 164 2 114 0 6 17 −11 23 0.259 0.73 −0.5 −34
001009 20 048 5 254 0 78 26 52 104 1.233 0.41 0.8 −52
001010 18 282 4 668 0 57 296 −239 353 0.993 5.16 −4.2 −592
001011 36 822 12 363 0 110 355 −245 465 0.895 2.89 −2.0 −710
002001 460 793 197 111 0 364 550 −186 914 0.221 0.33 −0.1 −1 100
002002 932 001 384 781 0 1 006 1 518 −512 2 524 0.306 0.46 −0.2 −3 036
002003 95 638 39 811 0 102 42 60 144 0.301 0.12 0.2 −84
002004 1 543 644 650 723 0 1 050 2 516 −1 466 3 566 0.191 0.46 −0.3 −5 032
002005 91 309 38 424 0 99 44 55 143 0.305 0.14 0.2 −88
003001 70 358 28 691 0 18 47 −29 65 0.073 0.19 −0.1 −94
003002 58 624 24 829 0 45 280 −235 325 0.216 1.34 −1.1 −560
003003 249 303 109 569 0 107 984 −877 1 091 0.119 1.10 −1.0 −1 968
003008 238 498 116 768 0 412 1 099 −687 1 511 0.464 1.24 −0.8 −2 198
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
mapview 2.11.0 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.